package com.xw.class09;

import java.util.Stack;

/**
 * @author: xw
 * @create: 2023/6/1 17:34
 * @description: 判断一个链表是否是回文结构
 */
public class Code02_IsPalindromeList {
    public static class Node {
        public int value;
        public Node next;

        public Node(int v) {
            value = v;
        }
    }

    public static boolean isPalindrome1(Node head){
        if (head == null) {
            return false;
        }
        Stack<Node> stack = new Stack<>();
        Node cur = head;
        while (cur.next != null) {
            stack.push(cur);
            cur = cur.next;
        }
        while (head != null) {
            Node pop = stack.pop();
            if(head.value != pop.value){
                return false;
            }
            head = head.next;
        }
        return true;
    }

    /**
     * 不用栈的情况下判断链表是否是回文表 快慢指针(确定中点)，调整为两个指向中间节点的链表，然后在判断是否是回文
     * @param head
     * @return
     */
    public static boolean isPalindrome2(Node head){
        if (head == null || head.next == null) {
            return true;
        }
        Node n1 = head;
        Node n2 = head;
        while(n2.next != null && n2.next.next != null  ){
            n1 = n1.next;
            n2 = n2.next.next;
        }

        //调整顺序
        n2 = n1.next;
        n1.next = null;
        Node n3;
        while (n2 != null){
            n3 = n2.next;
            n2.next = n1;
            n1 = n2;
            n2 = n3;
        }
        //记录尾节点开始比较
        n3 = n1;
        n2 = head;
        boolean res = true;
        while (n2 != null && n1 != null){
            if(n1.value != n2.value){
                res = false;
                break;
            }
            n1 = n1.next;
            n2 = n2.next;
        }
        //恢复链表
        n1 = n3.next;
        n3.next = null;
        while (n1 != null) {
            n2 = n1.next;
            n1.next = n3;
            n3 = n1;
            n1 = n2;
        }
        return res;
    }
}
